<?php

namespace App\Http\Middleware;

use App\Common\Status;
use App\Http\Logic\PC\AuthLogic;
use Closure;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;


class PCAuth
{
    /**
     * Handle an incoming request.
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $header = $request->header('Authorization');
        if (!$header) {
            return response()->json([
                'code' => Status::JWT_TOKEN['heard_nil'],
                'msg'  => "未获取到 Authorization 头信息"
            ])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }

        try {
            if (!$pcInfo = JWTAuth::parseToken()->getPayload()) {
                return response()->json([
                    'code' => Status::JWT_TOKEN['unknow'],
                    'msg'  => "无此用户"
                ])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
            }

            $decInfo = json_decode($pcInfo, true);
            $uInfo   = json_decode($decInfo['uid'], true);
            if (!isset($uInfo['user_id'])) {
                return response()->json([
                    'code' => Status::JWT_TOKEN['err'],
                    'msg'  => "用户帐号异常"
                ])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
            }
//            if (!$decInfo['mobile']) {
//                return response()->json([
//                    'code' => Status::JWT_TOKEN['mobile_err'],
//                    'msg'  => "解析失败 用户手机号有误"
//                ])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
//            }

//            $pcUser = AuthLogic::loginCheck($decInfo['mobile']);
//
//            if (!$pcUser) {
//                return response()->json([
//                    'code' => Status::JWT_TOKEN['empty'],
//                    'msg'  => "用户不存在"
//                ])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
//            }

            return $next($request);

        } catch (TokenExpiredException $e) {

            return response()->json([
                'code' => Status::JWT_TOKEN['expire'],
                'msg'  => "token已过期"
            ])->setEncodingOptions(JSON_UNESCAPED_UNICODE);

        } catch (TokenInvalidException $e) {
            return response()->json([
                'code' => Status::JWT_TOKEN['invalid'],
                'msg'  => "token无效"
            ])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        } catch (JWTException $e) {
            return response()->json([
                'code' => Status::JWT_TOKEN['empty'],
                'msg'  => "token为空"
            ])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }
    }
}
